<?php
namespace app\admin\controller;
use app\admin\controller\Base;
use app\service\billService;
use app\service\repairService;
use app\service\roominfoService;
use app\service\homeService;
use app\service\apiService;
use app\service\apixcxService;
use app\service\appletService;
use think\Db;
use think\Controller;

use printing\printDemo;
use app\service\xcxService;
use think\Request;
use think\Log;
class H5wxpay extends Basewx{
	public function selectroom(){
		
		//session("url",request()->url());
		
		$community_id=request()->get("community_id");
		$communityinfo=Db::table("community")->where("id",$community_id)->find();
		if(empty($communityinfo)){
		    return "小区信息错误";
			$this->error("小区信息错误");
		}
		if($communityinfo["is_support_wechat"]=="0"){
		    return $this->fetch("nosupport");
		    return "该小区不支持微信支付";
		}
		$this->assign("communityinfo",$communityinfo);

		$group = (new xcxService())->groupList($communityinfo["community_id"]);
		
		$str="[";
		foreach ($group as $key => $value) {
			$str=$str."'".$value."',";
		}
		$str=$str."]";
		
		$this->assign("str",$str);
		return $this->fetch();
	}

	public function getbuilding(){
		$community_id = request()->param('community_id');
        $group = request()->param('group');;
        $building = (new xcxService())->buildingList($group,$community_id);
        sort($building,SORT_NATURAL|SORT_STRING|SORT_FLAG_CASE);
        return $building;
	}
	public function getunit(){
		$community_id = request()->param('community_id');
        $group = request()->param('group');;
        $building = request()->param('building');
        $unit = (new xcxService())->unitList($building,$group,$community_id);
        sort($unit,SORT_NATURAL|SORT_STRING|SORT_FLAG_CASE);
        return $unit;
	}
	public function getroom(){
		$community_id = request()->param('community_id');
        $group = request()->param('group');;
        $building = request()->param('building');
        $unit = request()->param('unit');
        $room = (new xcxService())->roomList($unit,$building,$group,$community_id);
        sort($room,SORT_NATURAL|SORT_STRING|SORT_FLAG_CASE);
        return $room;
	}

	public function getroominfo(){
		$community_id = request()->param('community_id');
        $group = request()->param('group');;
        $building = request()->param('building');
        $unit = request()->param('unit');
        $room = request()->param('room');
        $roominfo=(new xcxService())->getroominfo($community_id,$group,$building,$unit,$room);
        if(empty($roominfo)){
        	$arr["errorCode"]="1";
        	$arr["errorMsg"]="请选择房屋";
        	echo json_encode($arr);
        	exit;
        }else{
        	$arr["errorCode"]="0";
        	$arr["roominfo"]=$roominfo;
        	echo json_encode($arr);
        	exit;
        }
	}

	public function billinfo(){
		session("url",request()->url());
		$id=request()->get("id");
		$roominfo=Db::table("roominfo")->where("id",$id)->find();
		$communityinfo=Db::table("community")->where("community_id",$roominfo["community_id"])->find();
		
		$roominfo["community_name"]=$communityinfo["community_name"];

		 //根据房号查询账单
        $billlis = (new appletService())->billRoomIdList($roominfo['out_room_id']);
        if(empty($billlis)){
			return $this->fetch("nopaymsg2");
		}
		//查询缴费类型
		$costtype = (new appletService())->cost_type($roominfo['out_room_id']);
		$billsum=(new appletService())->billsum($roominfo['out_room_id']);
		$billlist=array();
        foreach ($costtype as $b){
        	$arr["costtype"]=$b;
            $billinfo = (new appletService())->cost_type_bill($roominfo['out_room_id'],$b);
            $arr["billinfo"]=$billinfo;
            $billlist[]=$arr;
        }
        
		/*echo "<pre>";
		var_dump($billlist);
		die;*/
		$this->assign("billsum",$billsum);
		$this->assign("billlist",$billlist);
		$this->assign("roominfo",$roominfo);
		return $this->fetch();
	}

	//计算要缴费的金额
	public function moneysum(){
		$post=request()->post();
		$ordermoney=0;
		if(!(request()->has('billid'))){
			return json(['state'=>'1','info' => "0"]);
		}
		foreach ($post["billid"] as $key => $value) {
			$billinfo=Db::table("bill")->where('id',$value)->find();
			$ordermoney=$ordermoney+$billinfo["bill_entry_amount"];
		}
		$data["order_money"]=$ordermoney;
		
		
		$data["pay_money"]=round($data["order_money"],2);
		return json(['state'=>'1','info' => $data["pay_money"]]);
	}

	public function createOrder(){
		if(!(request()->has('billid'))){
			return json(['info' => '请选择要交费的账单']);
		}
		$post=request()->post();
		
		$billpay["billid"]=serialize($post["billid"]);
		$ordermoney=0;
		foreach ($post["billid"] as $key => $value) {
			$billinfo=Db::table("bill")->where('id',$value)->find();
			if($billinfo["status"]=="TRADE_SUCCESS"){
				return json(['info' => '该帐单已缴费']);
			}
			$ordermoney=$ordermoney+$billinfo["bill_entry_amount"];
		}
		$billpay["order_money"]=$ordermoney;
		$billpay["user_id"]=session("user_id");
		
		$billpay["out_room_id"]=$post["out_room_id"];
		$billpay["room_address"]=$post["room_address"];
		$billpay["community_id"]=$post["community_id"];
		$billpay["community_name"]=$post["community_name"];
		
		$billpay["pay_money"]=round($billpay["order_money"],2);
		$billpay["out_trade_no"]=date('YmdHiss').rand(100000,999999);

		
        $communityinfo = (new billService())->communityName($post["community_id"]);
        $propertyinfo = (new billService())->propertyInfo($communityinfo['property_id']);
        //生成订单
        $order['appid'] = $propertyinfo['wx_appid'];//公众账号ID
        $order['mch_id'] = $propertyinfo['wx_mch_id'];//商户号
        //根据停车场查询子商户ID
        $order['sub_mch_id'] = $communityinfo['sub_mch_id'];//子商户公众账号ID
        $order['nonce_str'] = $this->createNoncestr();//随机字符串
        $order['body'] = $billpay["community_name"].$billpay["room_address"].'物业缴费';;//商品描述
        $order['out_trade_no'] = date('YmdHis').rand(100000,999999);//商户订单号
        $order['total_fee'] = $billpay["pay_money"]*100;//总金额
        $order['spbill_create_ip'] = $_SERVER["REMOTE_ADDR"];//终端IP
        $order['notify_url'] = 'https://www.wuye.zfbzhsq.com/admin/callback/wxnotice';//通知url
        $order['trade_type'] = 'JSAPI';
        $order['openid'] = session("user_id");//用户标识
        $wxkey = $propertyinfo['wx_key'];//key
        $order['sign'] = $this->MakeSign($order,$wxkey);//签名
        //输出xml字符
        $xml = $this->ToXml($order);
        // return $xml;
        $url = 'https://api.mch.weixin.qq.com/pay/unifiedorder';
        //CURL模拟请求
        $curls = curl_init(); //启动一个CURL会话
        curl_setopt($curls, CURLOPT_URL, $url); //要访问的地址
        curl_setopt($curls, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curls, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($curls, CURLOPT_HEADER, FALSE);//设置header
        curl_setopt($curls, CURLOPT_RETURNTRANSFER, TRUE);//要求结果为字符串且输出到屏幕上
        curl_setopt($curls, CURLOPT_POST, TRUE); //发送一个常规的Post请求
        curl_setopt($curls, CURLOPT_POSTFIELDS, $xml); //Post提交的数据包
        curl_setopt($curls, CURLOPT_TIMEOUT, 30); //设置超时限制防止死循环
        $payInfo = curl_exec($curls); //执行操作
        // $err = curl_error($curls);//输出错误
        curl_close($curls); //关闭CURL会话
        $payInfo = json_decode(json_encode(simplexml_load_string($payInfo, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
        //Log::write($payInfo,"payinfo");
        if($payInfo['return_code'] !== 'SUCCESS'){
            return $payInfo['return_msg'];
        }else{
            
            $billpay['trade_no'] =  $order['out_trade_no'];
			
			$billpay["scenes"]=4;	
			$res=Db::table("billpay")->insert($billpay);
			
            //返回结果到前台唤起收银台
            if($res){
                $jsApiParameters['appId'] = $payInfo['appid'];
                $jsApiParameters['timeStamp'] = time();
                // $jsApiParameters['nonceStr'] = $payInfo['nonce_str'];
                $jsApiParameters['nonceStr'] = $this->createNoncestr();
                $jsApiParameters['package'] = 'prepay_id='.$payInfo['prepay_id'];
                $jsApiParameters['signType'] = 'MD5';
                // $jsApiParameters['paySign'] = $payInfo['sign'];
                $jsApiParameters['paySign'] = $this->MakeSigns($jsApiParameters,$wxkey);
                return json(['jsApiParameters' => json_encode($jsApiParameters)]);
            }else{
                return json(['info' => '订单存储失败']);
            }
        }
	}
    public function gatepay(){
        session("url",request()->url());
        if(request()->isPost()){
	        $gateid=request()->post("gateid");
    	    $gateinfo=Db::table("property_parking_gate")->where("id",$gateid)->find();
    	    $propertyinfo=Db::table("property")->where("id",$gateinfo["property_id"])->find();
	        $info["gateid"]=$gateinfo["id"];
	        $info["property_id"]=$gateinfo["property_id"];
	        $info["gateName"]=$gateinfo["gateName"];
    		$info["user_id"]=session("user_id");
	        $info["order_money"]=request()->post("pay_money");
    		$info["user_id"]=session("user_id");
    		$info["community_name"]=$gateinfo["community_name"];
    		$info["pay_money"]=request()->post("pay_money");
    		$info["out_trade_no"]=date('YmdHiss').rand(100000,999999);
            $info["subject"] = $gateinfo["community_name"]."-".$gateinfo["gateName"];
    		
            //生成订单
            $order['appid'] = $propertyinfo['wx_appid'];//公众账号ID
            $order['mch_id'] = $propertyinfo['wx_mch_id'];//商户号
            //根据停车场查询子商户ID
            $order['sub_mch_id'] = $gateinfo['sub_mch_id'];//子商户公众账号ID
            $order['nonce_str'] = $this->createNoncestr();//随机字符串
            $order['body'] = $info["subject"];//商品描述
            $order['out_trade_no'] =$info["out_trade_no"];//商户订单号
            $order['total_fee'] = $info["pay_money"]*100;//总金额
            $order['spbill_create_ip'] = $_SERVER["REMOTE_ADDR"];//终端IP
            $order['notify_url'] = 'https://www.wuye.zfbzhsq.com/admin/callback/wxgatepayNotice';//通知url
            $order['trade_type'] = 'JSAPI';
            $order['openid'] = session("user_id");//用户标识
            $wxkey = $propertyinfo['wx_key'];//key
            $order['sign'] = $this->MakeSign($order,$wxkey);//签名
            //输出xml字符
            $xml = $this->ToXml($order);
            // return $xml;
            $url = 'https://api.mch.weixin.qq.com/pay/unifiedorder';
            //CURL模拟请求
            $curls = curl_init(); //启动一个CURL会话
            curl_setopt($curls, CURLOPT_URL, $url); //要访问的地址
            curl_setopt($curls, CURLOPT_SSL_VERIFYPEER, FALSE);
            curl_setopt($curls, CURLOPT_SSL_VERIFYHOST, FALSE);
            curl_setopt($curls, CURLOPT_HEADER, FALSE);//设置header
            curl_setopt($curls, CURLOPT_RETURNTRANSFER, TRUE);//要求结果为字符串且输出到屏幕上
            curl_setopt($curls, CURLOPT_POST, TRUE); //发送一个常规的Post请求
            curl_setopt($curls, CURLOPT_POSTFIELDS, $xml); //Post提交的数据包
            curl_setopt($curls, CURLOPT_TIMEOUT, 30); //设置超时限制防止死循环
            $payInfo = curl_exec($curls); //执行操作
            // $err = curl_error($curls);//输出错误
            curl_close($curls); //关闭CURL会话
            $payInfo = json_decode(json_encode(simplexml_load_string($payInfo, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
            //Log::write($payInfo,"payinfo");
            if($payInfo['return_code'] !== 'SUCCESS'){
                return $payInfo['return_msg'];
            }else{
                
                $info['trade_no'] =  $order['out_trade_no'];
                $info['pay_type']=2;
    			$res=Db::table("billpark")->insert($info);
    			
                //返回结果到前台唤起收银台
                if($res){
                    $jsApiParameters['appId'] = $payInfo['appid'];
                    $jsApiParameters['timeStamp'] = time();
                    // $jsApiParameters['nonceStr'] = $payInfo['nonce_str'];
                    $jsApiParameters['nonceStr'] = $this->createNoncestr();
                    $jsApiParameters['package'] = 'prepay_id='.$payInfo['prepay_id'];
                    $jsApiParameters['signType'] = 'MD5';
                    // $jsApiParameters['paySign'] = $payInfo['sign'];
                    $jsApiParameters['paySign'] = $this->MakeSigns($jsApiParameters,$wxkey);
                    return json(['jsApiParameters' => json_encode($jsApiParameters)]);
                }else{
                    return json(['info' => '订单存储失败']);
                }
            }
	        
	    }else{
	        $gateid=request()->get("gateid");
    	    $gateinfo=Db::table("property_parking_gate")->where("id",$gateid)->find();
    	    $this->assign("gateinfo",$gateinfo);
    	    return $this->fetch();
	    }
    }
    
    
	public function billinfo_discount(){
		session("url",request()->url());
		$id=request()->get("id");
		$roominfo=Db::table("roominfo")->where("id",$id)->find();
		$communityinfo=Db::table("community")->where("community_id",$roominfo["community_id"])->find();
		
		$roominfo["community_name"]=$communityinfo["community_name"];

		 //根据房号查询账单
        $billlis = (new appletService())->billRoomIdList($roominfo['out_room_id']);
        if(empty($billlis)){
			return $this->fetch("nopaymsg");
		}
		//查询缴费类型
		$costtype = (new appletService())->cost_type($roominfo['out_room_id']);
		$billsum=(new appletService())->billsum($roominfo['out_room_id']);
		if($communityinfo["discount_status"]=="1")
		{

			$billsum1=Db::name('bill')
							->where('out_room_id',$roominfo['out_room_id'])
							->where('status','WAIT_PAYMENT')
							->where('discount_status','1')
							->sum('bill_entry_amount');
			$billsum2=Db::name('bill')
							->where('out_room_id',$roominfo['out_room_id'])
							->where('status','WAIT_PAYMENT')
							->where('discount_status','2')
							->sum('bill_entry_amount');
			$billsum=round($billsum1*$communityinfo["discount_rate"],1)+$billsum2;
		}
		$billlist=array();
        foreach ($costtype as $b){
        	$arr["costtype"]=$b;
            $billinfo = (new appletService())->cost_type_bill($roominfo['out_room_id'],$b);
            $arr["billinfo"]=$billinfo;
            $billlist[]=$arr;
        }
		$this->assign("billsum",$billsum);
		$this->assign("billlist",$billlist);
		$this->assign("roominfo",$roominfo);
		$this->assign("communityinfo",$communityinfo);
		return $this->fetch("billinfo_discount");
	}
	//计算要缴费的金额
	public function moneysum_discount(){
		$post=request()->post();
		$ordermoney=0;
		if(!(request()->has('billid'))){
			return json(['state'=>'1','info' => "0"]);
		}
		//
		$community_id=request()->post("community_id");
		$communityinfo=Db::table("community")->where("community_id",$community_id)->find();
		foreach ($post["billid"] as $key => $value) {
			$billinfo=Db::table("bill")->where('id',$value)->find();
			$money=$billinfo["bill_entry_amount"];
			if(($communityinfo["discount_status"]=="1")&&($billinfo["discount_status"]=="1"))
			{
				$money=round($billinfo["bill_entry_amount"]*$communityinfo["discount_rate"],1);
			}
			$ordermoney=$ordermoney+$money;
		}
		$data["order_money"]=$ordermoney;
		
		
		$data["pay_money"]=round($data["order_money"],1);
		return json(['state'=>'1','info' => $data["pay_money"]]);
	}

	public function createOrder_discount(){
		if(!(request()->has('billid'))){
			return json(['info' => '请选择要交费的账单']);
		}
		$post=request()->post();
		$billpay["billid"]=serialize($post["billid"]);

		$community_id=request()->post("community_id");
		$communityinfo=Db::table("community")->where("community_id",$community_id)->find();
		

		$ordermoney=0;
		$discount_billid=array();
		foreach ($post["billid"] as $key => $value) {
			$billinfo=Db::table("bill")->where('id',$value)->find();
			if($billinfo["status"]=="TRADE_SUCCESS"){
				return json(['info' => '该帐单已缴费']);
			}
			$money=$billinfo["bill_entry_amount"];
			if(($communityinfo["discount_status"]=="1")&&($billinfo["discount_status"]=="1"))
			{
				$money=round($billinfo["bill_entry_amount"]*$communityinfo["discount_rate"],2);
				$arr["discount_status"]=1;
				$arr["money"]=$money;
				$arr["discount_rate"]=$communityinfo["discount_rate"];
				$discount_billid[$value]=$arr;
			}else{
				$arr["discount_status"]=2;
				$arr["money"]="";
				$arr["discount_rate"]="";
				$discount_billid[$value]=$arr;
			}
			$ordermoney=$ordermoney+$money;
		}
		$billpay["order_money"]=$ordermoney;
		$billpay["user_id"]=session("user_id");
		$billpay["discount_billid"]=json_encode($discount_billid);
		$billpay["out_room_id"]=$post["out_room_id"];
		$billpay["room_address"]=$post["room_address"];
		$billpay["community_id"]=$post["community_id"];
		$billpay["community_name"]=$post["community_name"];
		
		$billpay["pay_money"]=round($billpay["order_money"],1);
		$billpay["out_trade_no"]=date('YmdHiss').rand(100000,999999);

		$token = (new xcxService())->token($billpay["community_id"]);
        $subject = $billpay["community_name"].$billpay["room_address"].'物业缴费';
        $api = new apixcxService();
        $notifyUrl="https://www.jfzhiwen.com/admin/callback/alinotice_discount";
        $result = $api->create(json_encode(['out_trade_no'=> $billpay["out_trade_no"],'total_amount'=>$billpay["pay_money"],'buyer_id'=>$billpay["user_id"],'subject' =>$subject,'token'=>$token ,'notifyUrl'=>$notifyUrl]));
		if(property_exists($result,'sub_msg')){	
			return json(['info' => $result->sub_msg]);
		}else{
			$billpay['trade_no'] =  $result->trade_no;
			
			$billpay["scenes"]=3;	
			$res=Db::table("billpay")->insert($billpay);
			//返回结果到前台唤起收银台
			if($res){
				return json(['order_no' => $billpay['trade_no']]);
			}else{
				return json(['info' => '订单存储失败']);
			}
		}	
	}
	
	//产生随机字符串，不长于32位
    public function createNoncestr($length = 32){
        $chars = "abcdefghijklmnopqrstuvwxyz0123456789";
        $str = "";
        for ($i = 0; $i < $length; $i++)
        {
            $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
        }

        return $str;
    }
    //生成签名
    protected function MakeSign($arr,$wxkey){
        //签名步骤一：按字典序排序参数
        ksort($arr);
        $string = $this->ToUrlParams($arr);
        //签名步骤二：在string后加入KEY
        $string = $string . "&key=" . $wxkey;
        //签名步骤三：MD5加密
        $string = md5($string);
        //签名步骤四：所有字符转为大写
        $result = strtoupper($string);
        return $result;
    }
    //生成签名
    protected function MakeSigns($arr,$wxkey){
        //签名步骤一：按字典序排序参数
        ksort($arr);
        $string = $this->ToUrlParams($arr);
        //签名步骤二：在string后加入KEY
        $string = $string . "&key=" . $wxkey;
        //签名步骤三：MD5加密
        $result = md5($string);
        return $result;
    }
    //格式化参数格式化成url参数
    public function ToUrlParams($value){
        $buff = "";
        foreach($value as $k => $v){
            if($k != "sign" && $v != "" && !is_array($v)){
                $buff .= $k . "=" . $v . "&";
            }
        }
        $buff = trim($buff, "&");
        return $buff;
    }
    //输出xml字符
    public function ToXml($arr){
        $xml = "<xml>";
        foreach ($arr as $key => $val){
            if (is_numeric($val)){
                $xml .= "<" . $key . ">" . $val . "</" . $key . ">";
            }else{
                $xml .= "<" . $key . "><![CDATA[" . $val . "]]></" . $key . ">";
            }
        }
        $xml .= "</xml>";
        return $xml;
    }
}